package home

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"minititok/Entities"
	"minititok/Services"
	"net/http"
	"strconv"
	"time"
)

func getComments(c *gin.Context) {
	type RequestBody struct {
		TargetTime string `json:"targetTime"`
		Av         string `json:"av"`
	}
	var body RequestBody
	if err := c.ShouldBindJSON(&body); err != nil {
		_ = c.Error(fmt.Errorf("请求错误:" + err.Error()))
		c.JSON(http.StatusBadRequest, gin.H{"customMessage": "请求不正确"})
		return
	}
	av := body.Av
	av = av[2:]
	targetTime, err := time.Parse(time.RFC3339, body.TargetTime)
	if err != nil {
		_ = c.Error(fmt.Errorf("时间格式错误:" + err.Error()))
		c.JSON(http.StatusBadRequest, gin.H{"customMessage": "时间格式错误"})
		return
	}
	comments, err := Services.GetFiveCommentsByAvAndTime(av, targetTime)
	if err != nil {
		_ = c.Error(fmt.Errorf("数据库错误,评论获取失败:" + err.Error()))
		c.JSON(http.StatusInternalServerError, gin.H{"customMessage": "评论获取失败"})
		return
	}
	data := gin.H{
		"data": []gin.H{},
	}
	var items []gin.H
	if len(comments) > 0 {
		if len(comments) < 4 {
			data["has_more"] = false
		} else {
			data["has_more"] = true
		}
	}
	for _, item := range comments {
		currUser, _ := Services.FindUserByUsername(item.Username)
		items = append(items, gin.H{
			"id":  item.ID,
			"uid": currUser.UID,
			"user": gin.H{
				"nickname": currUser.Nickname,
				"avatar":   currUser.Avatar,
			},
			"content":    item.Content,
			"createTime": item.Created,
		})
	}
	data["data"] = items
	c.JSON(http.StatusOK, data)
}

func giveComment(c *gin.Context) {
	type RequestBody struct {
		Comments string `json:"comments"`
		Av       string `json:"av"`
	}
	var body RequestBody
	if err := c.ShouldBindJSON(&body); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"customMessage": "请求错误"})
	}
	av := body.Av
	av = av[2:]
	user, _ := c.Get("user")
	currUser, _ := user.(*Entities.User)
	err := Services.CreateNewComment(av, currUser.Username, body.Comments)
	if err != nil {
		_ = c.Error(fmt.Errorf("数据库错误,评论失败:" + err.Error()))
		c.JSON(http.StatusInternalServerError, gin.H{"customMessage": "评论失败,请检查评论是否正确"})
		return
	}
	intAv, _ := strconv.Atoi(av)
	currVideo, _ := Services.FindVideoByAV(int64(intAv))
	countErr := Services.CountComments(currVideo)
	if countErr != nil {
		_ = c.Error(fmt.Errorf("数据库错误,计数失败:%w", err))
		log.Println(countErr)
	}
	c.JSON(http.StatusOK, gin.H{"customMessage": "成功"})
}
